<template>
  <div id="app">
    <div class="chat-box" ref="chatBox">
      <div class="messages" ref="messages">
<!--        <div v-for="(message, index) in messages" :key="index" class="message">-->
<!--          {{ message }}-->
<!--        </div>-->
        <vue-markdown :source="markdownText"></vue-markdown>
      </div>
    </div>
    <div class="input-box">
      <input v-model="newMessage" placeholder="Type a message..." />
      <el-button type="primary" @click="sendMessage" :loading="sendLoading" size="mini">发送</el-button>
    </div>
  </div>
</template>



<script>
import {sendContent,createImage} from "@/api/ai/qianfan";
import VueMarkdown from 'vue-markdown'
// import 'vue-markdown/dist/vue-markdown.css' // 引入样式文件
export default {
  data() {
    return {
      messages: [],
      newMessage: '',
      sendLoading:false,
      markdownText: ""
    };
  },
  components: {
    VueMarkdown
  },
  methods: {
    sendMessage() {
      if (this.newMessage.trim() !== '') {
        let newMessage = this.newMessage
        // this.messages.push(`You: ${newMessage}`);
        this.markdownText += `You: ${newMessage}`+"\n"
        this.newMessage = '';

        this.sendLoading = true

        sendContent({content:newMessage}).then(res=>{
          console.log('返回信息',res)

          // this.messages.push(`AI: ${res.data.result}`);
          this.markdownText += `AI: ${res.data.result}`+"\n"

          this.sendLoading = false
          this.scrollChatToBottom();
        }).catch(e=>{
          this.sendLoading = false
          this.messages.push(e);
        })


      }
    },
    scrollChatToBottom() {
      this.$nextTick(() => {
        const chatBox = this.$refs.chatBox;

        console.log("Scrolling to bottom");
        console.log("chatBox.scrollTop:", chatBox.scrollTop);
        console.log("chatBox.scrollHeight:", chatBox.scrollHeight);
        chatBox.scrollTop = chatBox.scrollHeight;
        console.log("chatBox.scrollTop:", chatBox.scrollTop);
      });
    }
  }
};
</script>

<style>
#app {
  display: flex;
  flex-direction: column;
  height: 80vh;
  justify-content: space-between;
  margin: 20px; /* 增加整体上下文的间距 */
}

.chat-box {
  flex: 1;
  border: 1px solid #ccc;
  overflow-y: scroll;
  padding: 10px;
  max-height: 70vh;
  margin-bottom: 10px; /* 增加聊天框与输入框的下边距 */
}

.message{
  padding: 10px 0;
}

.input-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin-top: 10px; /* 增加输入框与聊天框的上边距 */
}

input {
  flex: 1;
  padding: 5px;
  margin-right: 10px;
}

button {
  padding: 5px 10px;
}

code {
  background-color: #f0f0f0; /* 自定义背景颜色 */
}
</style>


